define(['angularAMD'],
    function(angularAMD) {
        // 使用严格模式
        'use strict';

        var app = angular.module('appCRM', ['ngRoute', 'ngResource', 'ngAnimate', 'ngSanitize', 'angular-data.DSCacheFactory', 'pascalprecht.translate', 'cgBusy']);

        /* application constant define */
        app.constant('crmConst', {
            BASE: '/',
            API: 'Admin/',
            APP_NAME: '和众汇富CRM3',
            APP_VERSION: '1.5',
            CAREER: [{ k: 0, v: '未知' }, { k: 1, v: '老师' }, { k: 2, v: '司机' }, { k: 3, v: '律师' }, { k: 4, v: '医生' }, { k: 5, v: '公务员' }, { k: 6, v: '厨师' }, { k: 7, v: '自由工作者' },
                { k: 8, v: '个体户' }, { k: 9, v: '无业' }, { k: 10, v: '其他' }
            ],
            EDUCATION: [{ k: 0, v: '未知' }, { k: 1, v: '小学' }, { k: 2, v: '初中' }, { k: 3, v: '高中' }, { k: 4, v: '大学' }, { k: 5, v: '硕士研究生' }, { k: 6, v: '博士研究生' }]
        });

        app.config(function($routeProvider, $compileProvider, crmConst) {
            $routeProvider
                .when("/home", angularAMD.route({
                    templateUrl: "views/home.html" + '?v' + crmConst.APP_VERSION,
                    controller: "Home",
                    controllerUrl: "HomeController"
                }))
                .when("/login", angularAMD.route({
                    templateUrl: "views/login.html"+ '?v' + crmConst.APP_VERSION,
                    controller: "Login",
                    controllerUrl: "LoginController"
                }))
                .when('/sector', angularAMD.route({
                    templateUrl: "views/sector.html" + '?v' + crmConst.APP_VERSION ,
                    controller: "Sector",
                    controllerUrl: "js/controllers/sector"
                }))
                .when('/user', angularAMD.route({
                    templateUrl: 'views/user.html' + '?v' + crmConst.APP_VERSION ,
                    controller: 'User',
                    controllerUrl: "js/controllers/user"
                }))
                .when('/log', angularAMD.route({
                    templateUrl: 'views/log.html' + '?v' + crmConst.APP_VERSION,
                    controller: 'Log',
                    controllerUrl: "js/controllers/log"
                }))
                .when('/event', angularAMD.route({
                    templateUrl: 'views/event.html' + '?v' + crmConst.APP_VERSION,
                    controller: 'Event',
                    controllerUrl: "js/controllers/event"
                }))
                .when('/dashboard', angularAMD.route({
                    templateUrl: 'views/dashboard.html' + '?v' + crmConst.APP_VERSION,
                    controller: 'Dashboard',
                    controllerUrl: "js/controllers/dashboard"
                }))
                .when('/role', angularAMD.route({
                    templateUrl: 'views/role.html' + '?v' + crmConst.APP_VERSION,
                    controller: 'Role',
                    controllerUrl: "js/controllers/role"
                }))
                .when('/right', angularAMD.route({
                    templateUrl: 'views/right.html' + '?v' + crmConst.APP_VERSION,
                    controller: 'Right',
                    controllerUrl: "js/controllers/right"
                }))
                .when('/source', angularAMD.route({
                    templateUrl: 'views/source.html' + '?v' + crmConst.APP_VERSION,
                    controller: 'Source',
                    controllerUrl: "js/controllers/source"
                }))
                .when('/productline', angularAMD.route({
                    templateUrl: 'views/productline.html' + '?v' + crmConst.APP_VERSION,
                    controller: 'ProductLine',
                    controllerUrl: "js/controllers/productline"
                }))
                .when('/product/:product_line_code', angularAMD.route({
                    templateUrl: 'views/product.html' + '?v' + crmConst.APP_VERSION,
                    controller: 'Product',
                    controllerUrl: "js/controllers/product"
                }))
                .when('/product', angularAMD.route({
                    templateUrl: 'views/product.html' + '?v' + crmConst.APP_VERSION,
                    controller: 'Product',
                    controllerUrl: "js/controllers/product"
                }))
                .when('/product_package', angularAMD.route({
                    templateUrl: 'views/product_package.html' + '?v' + crmConst.APP_VERSION,
                    controller: 'ProductPackage',
                    controllerUrl: "js/controllers/product_package"
                }))
                .when('/product_package/:product_id', angularAMD.route({
                    templateUrl: 'views/product_package.html' + '?v' + crmConst.APP_VERSION,
                    controller: 'ProductPackage',
                    controllerUrl: "js/controllers/product_package"
                }))
                .when('/qyservice', angularAMD.route({
                    templateUrl: 'views/qyservice.html' + '?v' + crmConst.APP_VERSION,
                    controller: 'QyService',
                    controllerUrl: "js/controllers/qyservice"
                }))
                .when('/product_price', angularAMD.route({
                    templateUrl: 'views/product_price.html' + '?v' + crmConst.APP_VERSION,
                    controller: 'ProductPrice',
                    controllerUrl: "js/controllers/product_price"
                }))
                .when('/xufei', angularAMD.route({
                    templateUrl: 'views/xufei.html' + '?v' + crmConst.APP_VERSION,
                    controller: 'Xufei',
                    controllerUrl: "js/controllers/xufei"
                }))
                .when('/tags', angularAMD.route({
                    templateUrl: 'views/tags.html' + '?v' + crmConst.APP_VERSION,
                    controller: 'Tags',
                    controllerUrl: "js/controllers/tags"
                }))
                .when('/complain', angularAMD.route({
                    templateUrl: 'views/complain.html' + '?v' + crmConst.APP_VERSION,
                    controller: 'Complain',
                    controllerUrl: "js/controllers/complain"
                }))
                .when('/caiwu.money', angularAMD.route({
                    templateUrl: 'views/caiwu/money.html' + '?v' + crmConst.APP_VERSION,
                    controller: 'Caiwu.money',
                    controllerUrl: "js/controllers/caiwu.money"
                }))
                .when('/caiwu.refund', angularAMD.route({
                    templateUrl: 'views/caiwu/refund.html' + '?v' + crmConst.APP_VERSION,
                    controller: 'Caiwu.refund',
                    controllerUrl: "js/controllers/caiwu.refund"
                }))
                .when('/pays', angularAMD.route({
                    templateUrl: 'views/pays.html' + '?v' + crmConst.APP_VERSION,
                    controller: 'Pays',
                    controllerUrl: "js/controllers/pays"
                }))
                .when('/customer', angularAMD.route({
                    templateUrl: 'views/customer.html' + '?v' + crmConst.APP_VERSION,
                    controller: 'Customer',
                    controllerUrl: "js/controllers/customer"
                }))
                .when('/contract', angularAMD.route({
                    templateUrl: 'views/contract.html' + '?v' + crmConst.APP_VERSION,
                    controller: 'Contract',
                    controllerUrl: "js/controllers/contract"
                }))
                .when('/View360/:customerID', angularAMD.route({
                    templateUrl: 'views/view360.html' + '?v' + crmConst.APP_VERSION,
                    controller: 'View360',
                    controllerUrl: "js/controllers/view360"
                }))
                .when('/call', angularAMD.route({
                    templateUrl: 'views/call.html' + '?v' + crmConst.APP_VERSION,
                    controller: 'Call',
                    controllerUrl: "js/controllers/call"
                }))
                .when('/om', angularAMD.route({
                    templateUrl: 'views/om.html'+ '?v' + crmConst.APP_VERSION,
                    controller: 'Om',
                    controllerUrl: "js/controllers/om"
                }))
                .when('/goals', angularAMD.route({
                    templateUrl: 'views/goals.html'+ '?v' + crmConst.APP_VERSION,
                    controller: 'Goals',
                    controllerUrl: "js/controllers/goals"
                }))
                .when('/pk', angularAMD.route({
                    templateUrl: 'views/pk.html'+ '?v' + crmConst.APP_VERSION,
                    controller: 'Pk',
                    controllerUrl: "js/controllers/pk"
                }))
                .when('/userlog', angularAMD.route({
                    templateUrl: 'views/userlog.html'+ '?v' + crmConst.APP_VERSION,
                    controller: 'Userlog',
                    controllerUrl: "js/controllers/userlog"
                }))
                .when('/analysis', angularAMD.route({
                    templateUrl: 'views/analysis.html'+ '?v' + crmConst.APP_VERSION,
                    controller: 'Analysis',
                    controllerUrl: "js/controllers/analysis"
                }))
                .when('/invoice', angularAMD.route({
                    templateUrl: 'views/invoice.html'+ '?v' + crmConst.APP_VERSION,
                    controller: 'Invoice',
                    controllerUrl: "js/controllers/invoice"
                }))
                .when('/delivery', angularAMD.route({
                    templateUrl: 'views/delivery.html'+ '?v' + crmConst.APP_VERSION,
                    controller: 'Delivery',
                    controllerUrl: "js/controllers/delivery"
                }))
                .when('/delivery/:state1', angularAMD.route({
                    templateUrl: 'views/delivery.html'+ '?v' + crmConst.APP_VERSION,
                    controller: 'Delivery',
                    controllerUrl: "js/controllers/delivery"
                }))
                .when('/risk', angularAMD.route({
                    templateUrl: 'views/risk/index.html'+ '?v' + crmConst.APP_VERSION,
                    controller: 'Risk',
                    controllerUrl: "js/controllers/risk"
                }))
                .when('/refund', angularAMD.route({
                    templateUrl: 'views/refund/index.html'+ '?v' + crmConst.APP_VERSION,
                    controller: 'Refund',
                    controllerUrl: "js/controllers/refund"
                }))
                .when('/fine', angularAMD.route({
                    templateUrl: 'views/fine.html'+ '?v' + crmConst.APP_VERSION,
                    controller: 'Fine',
                    controllerUrl: "js/controllers/fine"
                }))
                .when('/violations', angularAMD.route({
                    templateUrl: 'views/violations.html'+ '?v' + crmConst.APP_VERSION,
                    controller: 'Violations',
                    controllerUrl: "js/controllers/violations"
                }))
                .when('/conflict', angularAMD.route({
                    templateUrl: 'views/conflict.html'+ '?v' + crmConst.APP_VERSION,
                    controller: 'Conflict',
                    controllerUrl: "js/controllers/conflict"
                }))
                .when('/knowledgeproperty', angularAMD.route({
                    templateUrl: 'views/knowledgeproperty.html'+ '?v' + crmConst.APP_VERSION,
                    controller: 'Knowledgeproperty',
                    controllerUrl: "js/controllers/knowledgeproperty"
                }))
                .when('/knowledgeright', angularAMD.route({
                    templateUrl: 'views/knowledgeright.html'+ '?v' + crmConst.APP_VERSION,
                    controller: 'Knowledgeright',
                    controllerUrl: "js/controllers/knowledgeright"
                }))
                .when('/viewknowledgenode/:knowledgeid/:msgtype/:knowledgespotid/:userid', angularAMD.route({
                    templateUrl: 'views/viewknowledgenode.html'+ '?v' + crmConst.APP_VERSION,
                    controller: 'Viewknowledgenode',
                    controllerUrl: "js/controllers/viewknowledgenode"
                }))
                .when('/qyapp', angularAMD.route({
                    templateUrl: 'views/qyapp.html'+ '?v' + crmConst.APP_VERSION,
                    controller: 'QyApp',
                    controllerUrl: "js/controllers/qyapp"
                }))
                .when('/qyapp/:qy_code', angularAMD.route({
                    templateUrl: 'views/qyapp.html'+ '?v' + crmConst.APP_VERSION,
                    controller: 'QyApp',
                    controllerUrl: "js/controllers/qyapp"
                }))
                .when('/qy', angularAMD.route({
                    templateUrl: 'views/qy.html'+ '?v' + crmConst.APP_VERSION,
                    controller: 'Qy',
                    controllerUrl: "js/controllers/qy"
                }))
                .when('/ordercustomer', angularAMD.route({
                    templateUrl: 'views/ordercustomer.html'+ '?v' + crmConst.APP_VERSION,
                    controller: 'OrderCustomer',
                    controllerUrl: "js/controllers/ordercustomer"
                }))
                .when('/ordercustomer/:package_code', angularAMD.route({
                    templateUrl: 'views/ordercustomer.html'+ '?v' + crmConst.APP_VERSION,
                    controller: 'OrderCustomer',
                    controllerUrl: "js/controllers/ordercustomer"
                }))
                .when("/:section", angularAMD.route({
                    templateUrl: function(rp) { return 'views/' + rp.section + '.html'+ '?v' + crmConst.APP_VERSION; },
                    resolve: {
                        load: ['$q', '$rootScope', '$location',
                            function($q, $rootScope, $location) {
                                var path = $location.path();
                                var parsePath = path.split("/");
                                var parentPath = parsePath[1];
                                var controllerName = parsePath[2];
                                var loadController = "js/controllers/" +
                                    parentPath.toLowerCase();

                                var deferred = $q.defer();
                                require([loadController], function() {
                                    $rootScope.$apply(function() {
                                        deferred.resolve();
                                    });
                                });
                                return deferred.promise;
                            }
                        ]
                    }
                }))
                .otherwise("/login");

            //Fix href unsafe link (added app to the white list)
            $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|app):/);
        });

        app.config(['$httpProvider', function($httpProvider) {
            $httpProvider.defaults.withCredentials = true;
        }]);

        //factory
        app.factory('account', function($q, appFactory, dataFactoryCRM) {
            var account = {};

            account.login = function(username, password, captioncode) {
                var deferred = $q.defer();
                sessionStorage.showHomeNotify = 0;
                appFactory.login(username, password, captioncode).then(function(response) {
                    if (response && response.rcode) {
                        sessionStorage.token = response["token"]; //temporally use user_no as Token
                        sessionStorage.username = response["data"]["nickname"];
                        sessionStorage.user = JSON.stringify(response["data"]); //storage只能存储字符串的数据
                        deferred.resolve(response);
                    } else {
                        deferred.reject(response);
                    }

                }, function(error) {
                    deferred.reject(error);
                });

                return deferred.promise;
            }

            account.logout = function() {
                return appFactory.logout().then(function() {
                    account.clear();
                })
            }

            account.clear = function() {
                dataFactoryCRM.destroyCache(); //注销时清理数据缓存
                sessionStorage.clear();
            }

            account.getToken = function() {
                return sessionStorage.token;
            }

            account.getUsername = function() {
                return sessionStorage.username;
            }

            account.getUser = function() {
                if (sessionStorage.user) {
                    return sessionStorage.user ? JSON.parse(sessionStorage.user) : null;
                } else
                    return null;
            }

            account.isConnected = function() {
                if (sessionStorage.token)
                    return true;

                return false;
            }

            return account;
        });

        app.config(['$httpProvider',
            function($httpProvider) {
                $httpProvider.interceptors.push(function($q, $location, $rootScope) {
                    return {
                        'request': function(config) {
                            return config;
                        },
                        'response': function(response) {
                            //Will only be called for HTTP up to 300
                            return response;
                        },
                        'responseError': function(rejection) {
                            if (401 == rejection.status) { //需要重新登录
                                $rootScope.$broadcast('userLoggedOut', null);
                                $location.path("/login");
                            } else if (404 == rejection.status || 500 == rejection.status) {
                                if (sessionStorage.token) {
                                    $('.modal.err404').remove();
                                    $("<div class='ui  basic modal err404'><div class='ui icon header'><i class='red warning circle icon'></i>" + rejection.status + "&nbsp;&nbsp;" + rejection.statusText + "</div></div>")
                                        .modal('show');
                                }
                                $rootScope.$broadcast("NOTBUSY");
                            } else if (403 == rejection.status) { //无权访问
                                if (sessionStorage.token) {
                                    $('.modal.err401').remove();
                                    $("<div class='ui  basic modal err401'><div class='ui icon header'><i class='red ban circle icon'></i>无权访问该模块!</div></div>")
                                        .modal('show');
                                }
                                $rootScope.$broadcast("NOTBUSY");
                            }
                            return $q.reject(rejection);
                        }
                    };
                });
            }
        ]);

        //AnimeDataService API
        app.factory('dataFactoryCRM', function($http, $sce, $cacheFactory, $q, DSCacheFactory, crmConst) {
            var dataFactory = {};

            //Prepare caching for better user experience
            DSCacheFactory('dataCache', {
                maxAge: 900000, // Items added to this cache expire after 15 minutes.
                cacheFlushInterval: 6000000, // This cache will clear itself every hour.
                deleteOnExpire: 'aggressive', // Items will be deleted from this cache right when they expire.
                storageMode: 'memory' // [default: memory] sessionStorage, localStorage
            });

            dataFactory.checkForInternetConnection = function(callback) {
                $http.get(crmConst.BASE).success(function(data) {
                    callback(true);
                }).error(function(e) {
                    callback(false);
                });
            }

            dataFactory.isServiceOnline = function(callback) {
                $http.get(crmConst.BASE + "ifServiceReady").success(function(data) {
                        callback(true);
                    })
                    .error(function(data, status) {
                        if (status == 401)
                            callback(true);
                        else
                            callback(false);
                    });
            }
            dataFactory.postDataByAPI = function(api_url, _data) {
                var query = crmConst.BASE + crmConst.API + api_url;
                var deferred = $q.defer();
                $http({
                        method: 'POST',
                        url: query,
                        transformRequest: function(obj) {
                            if (angular.isString(obj)) {
                                return obj;
                            } else if (angular.isObject(obj) || angular.isArray(obj)) {
                                return $.param(obj);
                            }
                        },
                        data: _data,
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }
                    }).success(function(response, status, headers, config) {
                        if (status == 200) {
                            deferred.resolve(response);
                        } else {
                            deferred.reject(response);
                        }
                    })
                    .error(function(error) {
                        deferred.reject(error);
                    });

                return deferred.promise;
            }

            dataFactory.getDataByAPI = function(api_url, do_not_cache) {

                var filter,
                    deferred = $q.defer(),
                    dataCache = DSCacheFactory.get('dataCache');

                var query = crmConst.BASE + crmConst.API + api_url;

                var ustr = sessionStorage.getItem("user");
                var udata = JSON.parse(ustr);
                var uid = 0;
                if (udata && udata.uid) { uid = udata.uid; }

                if (!do_not_cache && dataCache.get(query) && 0) {
                    deferred.resolve(dataCache.get(query));
                } else {
                    //Only animes with vk available
                    $http.get(query)
                        .success(function(data) {
                            if (!do_not_cache) {
                                dataCache.put(query, data);
                                //console.log('cache:' + query);
                            }
                            deferred.resolve(data);
                        }).error(function(error, status) {
                            deferred.reject();
                        });
                }

                return deferred.promise;
            }

            //重写
            dataFactory.getDataByAPIS = function(api_url, do_not_cache) {

                var filter,
                    deferred = $q.defer(),
                    dataCache = DSCacheFactory.get('dataCache');

                var query = crmConst.BASE + crmConst.API + api_url;

                var ustr = sessionStorage.getItem("user");
                var udata = JSON.parse(ustr);
                var uid = 0;
                if (udata && udata.uid) { uid = udata.uid; }

                if (!do_not_cache && dataCache.get(query) && 0) {
                    deferred.resolve(dataCache.get(query));
                } else {
                    //Only animes with vk available
                    $http.get(query, { responseType: "arraybuffer" })
                        .success(function(data) {
                            if (!do_not_cache) {
                                dataCache.put(query, data);
                                //console.log('cache:' + query);
                            }
                            deferred.resolve(data);
                        }).error(function(error, status) {
                            deferred.reject();
                        });
                }

                return deferred.promise;
            }

            dataFactory.destroyCache = function() {
                DSCacheFactory.clearAll();
            }

            return dataFactory;
        });

        //appService API
        app.factory('appFactory', function($http, $q, crmConst) {
            var rootFactory = {};

            //Login
            rootFactory.login = function(username, password, caption) {
                var loginUrl = crmConst.BASE + crmConst.API + 'login';
                var deferred = $q.defer();

                //Send login
                var formData = "username=" + username + "&password=" + password + "&caption=" + caption;

                $http({
                        method: 'POST',
                        url: loginUrl,
                        data: formData,
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }
                    }).success(function(response, status, headers, config) {
                        if (status == 200) {
                            deferred.resolve(response);
                        } else {
                            deferred.reject(response);
                        }
                    })
                    .error(function(error) {
                        deferred.reject(error);
                    });

                return deferred.promise;
            }

            //LogOut
            rootFactory.logout = function() {
                var logoutUrl = crmConst.BASE + crmConst.API + 'login/logout';
                var deferred = $q.defer();

                //Send logOut
                $http.get(logoutUrl)
                    .success(function(response, status, headers, config) {
                        if (status == 200) {
                            deferred.resolve(response);
                        } else {
                            deferred.reject(response);
                        }
                    })
                    .error(function(error) {
                        deferred.reject(error);
                    });

                return deferred.promise;
            }

            //Check if service is available
            rootFactory.isServiceOnline = function(callback) {
                $http.get(crmConst.BASE).success(function(data) {
                        callback(true);
                    })
                    .error(function(data, status) {
                        callback(false);
                    });
            }

            return rootFactory;
        });

        app.factory('settings', function($translate) {
            var settings = {};

            settings.defaults = {
                defaultLanguage: 'zh',
                useSecureConnection: false,
                languageMatch: false
            }
            return settings;
        });

        //app参数从后台加载参数
        //在appController中初始化加载
        app.service('crmParam', function($http, $q, crmConst) {
            var loaded = false;
            var data = {};
            data.data = [];

            data.get = function(key){
                if (!this.data)
                    init();
                return  (this.data&& key in this.data) ? this.data[key] :[]
            };

            var init = function(){
                    var paramApi = crmConst.BASE + crmConst.API + 'index/param';
                    $http.get( paramApi ).success(function(_d) {
                            data.data = _d;
                    });
                };
            init();
            return data;
        });

        app.config(function($translateProvider) {
            $translateProvider.translations('zh', {
                BTN_OK: '确定',
                BTN_CANCEL: '取消',
                NO_DATA: '没有找到符合条件的记录'
            });

            $translateProvider.preferredLanguage('zh');
        });

        app.directive('appmenu', ['$rootScope', '$interval', 'account', 'dataFactoryCRM', function($rootScope, $interval, account, dataFactoryCRM) {
            function link($scope, element, attrs) {
                $scope.menus = {};
                $scope.slide_status = 1;
                $scope.currentUrl = '';
                $scope.user = account.getUser();
                $scope.isConnected = $scope.user ? true : false;

                //从后端加载菜单配置
                $scope.appMenu = function() {
                    dataFactoryCRM.getDataByAPI('index/menu').then(function(d) {
                        if (d && d.rcode) {
                            $scope.menus = d.data;
                        }
                    });
                }

                if ($scope.isConnected) {
                    $scope.appMenu();
                }
                //用户退出登录
                $rootScope.$on('userLoggedOut', function(scope, data) {
                    $scope.isConnected = false;
                    $scope.menus = {};
                });

                //用户登录系统
                $rootScope.$on('userLoggedIn', function(scope, data) {
                    $scope.isConnected = true;
                    $scope.appMenu();
                });

                $scope.slide = function() {
                    if ($scope.slide_status) {
                        $scope.slide_status = 0;
                        $('.cont_fl').css("marginLeft", "-150px");
                        $('.leftPull').css("transform", "rotate(180deg)");
                        $('.leftPull').css("borderRadius", "5px 0 0 5px");
                    } else {
                        $scope.slide_status = 1;
                        $('.cont_fl').css("marginLeft", 0);
                        $('.leftPull').css("transform", "rotate(0)");
                        $('.leftPull').css("borderRadius", "0 5px 5px 0");
                    }
                }

                $scope.go = function(url, $event) {
                    $scope.currentUrl = url;
                    $rootScope.go(url);
                    $('.ui.accordion .menu .go_item').removeClass('active');
                     angular.element($event.target).addClass('active');
                }

                $rootScope.$on('$destroy', function() {
                    $scope.menus = {};
                });
            }
            return {
                restrict: 'E',
                templateUrl: 'views/directive/menu.html',
                scope: {},
                link: link
            }
        }]);

        //Angular busy (for loading)
        app.value('cgBusyDefaults', {
            message: 'Loading',
            backdrop: false
        });

        app.run(['$rootScope', '$window', '$location', '$log', '$http', function($rootScope, $window, $location, $log, $http) {
            $rootScope.$on('$routeChangeSuccess', routeChangeSuccess);
            $rootScope.$on('$routeChangeStart', routeChangeStart);
            $rootScope.psize = 20;

            $http.defaults.headers.common.Authorization = sessionStorage.token;

            function onRouteChangeStart(event, next, current) {
                // 如果下一个路由不允许匿名， 并且没有认证， 则重定向到 login 页面
                if (!next.allowAnonymous && !$rootScope.user) {
                    $log.log('Authentication required, redirect to login.');
                    var returnUrl = $location.url();
                    $log.log('return url is ' + returnUrl);
                    //
                    event.preventDefault();
                    $location.path('/login').search({ returnUrl: returnUrl });
                }
            }

            function routeChangeSuccess(event) {
                //记录当前最新路由地址，用于与新打开窗口交互判断
                window.currentRouteURL = $location.url();

                //$log.log('routeChangeSuccess');
                //处理semantic的modal烂摊子，清理多余的modal div
                $rootScope.clearModals();

                //确保菜单选中态正常，尤其针对非点击直接跳转/刷新场景
                var menus = $('.blue.inverted.menu a.item');
                for (var i = 0; i < menus.length; i++) {
                    var menu = menus[i];
                    if (menu.getAttribute('ng-href') == "#" + $location.$$url) {
                        if (!$(menu).hasClass('active')) {
                            menu.click();
                        }
                    }
                }
            };

            function routeChangeStart(event) {
                $('.modal').modal('hide');
            }

            $rootScope.go = function(url) {
                sessionStorage.lastUrl = url;
                $location.path(url);
            }


            //为当前页面新开独立无顶栏窗口
            $rootScope.openDetail = function(param, val, type, knowledgeid, userid) {

                if (param && val && !type && !knowledgeid && !userid) {
                    window.open("detail.html#/" + param + "/" + val);
                } else if (param && val && type && knowledgeid && userid) {
                    window.open("detail.html#/" + param + "/" + val + "/" + type + "/" + knowledgeid + "/" + userid);
                } else
                    window.open("detail.html#" + window.currentRouteURL);
            }

            //获取angular $scope
            window.getScope = function() {
                return $('#divDetail').scope();
            }

            //为独立窗口获取父窗口显示数据
            window.loadClientCacheToScope = function($scope, callback_for_no_parent) {


                $scope.$needClientCache = false;
                if (window.opener) {

                    //判断是否存在对应的父页面
                    $scope.$needClientCache = (window.currentRouteURL == window.opener.currentRouteURL);
                    //设置独立窗口标题
                    $('#detail_title').text($('#page_title').text());
                }

                if ($scope.$needClientCache) {
                    var test = window.opener.getScope().searchKey;
                    $("#nav li").removeClass("selected");
                    $(".state" + test).addClass("selected");
                    _deepCopy(window.opener.getScope(), $scope);
                } else {
                    callback_for_no_parent();
                }

                //深度拷贝
                function _deepCopy(fromObject, toObject) {　　　　
                    for (var key in fromObject) {
                        if (key.indexOf('$') >= 0)
                            continue;
                        if (Object.prototype.toString.call(fromObject[key]) === '[object Function]')
                            continue;
                        toObject[key] = fromObject[key];　　　　
                    }　　　　
                    return toObject;
                }
            }

            $rootScope.clearModals = function() {
                var modals = $('.ui.dimmer.modals');
                if (modals.length > 0) {
                    if (modals.children('#changepsw-model').length) {
                        modals.children('#changepsw-model').siblings().remove();
                    } else
                        modals[0].innerHTML = "";
                }
            }
        }]);

        app.controller('appController', function($rootScope, $scope, dataFactoryCRM, $location, $route, account, crmConst, $timeout, crmParam) {
            $rootScope.appInfo = crmConst;
            $scope.busy = false;
            $scope.logout = function() {
                account.logout().then(function() {
                    $rootScope.$broadcast('userLoggedOut', null);
                    $location.path('/login');
                }, function(reason) {
                    $rootScope.$broadcast('userLoggedOut', null);
                    $location.path('/login');
                });
            }

            //Load default
            loadUser();

            function loadUser() {
                $scope.isConnected = account.isConnected();
                $scope.user = account.getUser();
                if (!$scope.user || ($scope.user && !$scope.user.user_id)) {
                    account.clear()
                    $location.path('/login');
                    return;
                }
                $scope.currentUserName = sessionStorage.username;

                $scope.headerUrl = null;
                $scope.headerUrl = '';
            }


            $scope.changePSW = function() {
                    $('#frm-changepsw').find('.error').removeClass('error').find('.prompt').remove();
                    $scope.editUser = account.getUser();
                    $scope.editUser.old_psw = '';
                    $scope.editUser.password2 = '';
                    $scope.editUser.password1 = '';
                    $scope._upError = '';
                    $('.ui.editUser.modal').modal({
                        autofocus: false,
                        observeChanges: true,
                        onApprove: function(ele) {
                            if (!$('#frm-changepsw').form('is valid'))
                                return false;
                            dataFactoryCRM.postDataByAPI('index/updateUser', $scope.editUser)
                                .then(function(d) {
                                    if (d && d.rcode == 1) {
                                        sessionStorage.username = d.data.nickname;
                                        sessionStorage.user = JSON.stringify(d.data);
                                        loadUser();
                                        $('.ui.editUser.modal').modal('hide');
                                        $('<div class="ui small modal modal1" style="text-align: center;"><div class="header">提示</div><div class="content"><i class="huge green check circle outline icon"></i>' +
                                            '<p style="padding-top: 15px;">更新个人资料成功</p>' + '</div></div>'
                                        ).modal('show');
                                    } else if (d && d.rcode == 2) {
                                        //更新密码成功，退出重新登陆
                                        $('.ui.editUser.modal').modal('hide');
                                        $('<div class="ui small modal modal1" style="text-align: center;"><div class="header">提示</div><div class="content"><i class="huge green check circle outline icon"></i>' +
                                            '<p style="padding-top: 15px;">更新密码成功，退出重新登陆</p>' + '</div></div>'
                                        ).modal('show');
                                        $scope.logout();
                                    } else {
                                        $scope._upError = d.msg;
                                        $timeout(function() {
                                            $scope._upError = '';
                                        }, 2000);
                                    }
                                });
                            return false;
                        },

                    }).modal('show');
                }
                //查看合同详情
            $scope.showContractDetail = function(contractId) {
                var url = 'Contract/mail?contract_id=' + contractId;
                dataFactoryCRM.getDataByAPI(url)
                    .then(function(data) {
                        $scope.view = data.customer;
                        $scope.sum_money = data.sum_money;
                        $scope.payrecord = data.payrecord;
                        $scope.refund = data.refund;
                        if ($scope.refund)
                            $scope.mail_refund = false;
                        else
                            $scope.mail_refund = true;
                        if (data.rcode) {
                            $scope.view_child = data.delivery;
                            $scope.mail_record = false;
                        } else {
                            $scope.view_child = '';
                            $scope.mail_record = true;
                        }
                    })
                $('.ui.viewContractInfo.modal').modal({ observeChanges: true }).modal('show');
            }

            $scope.refresh = function() {
                dataFactoryCRM.destroyCache();
                $route.reload();
            }

            $scope.needMoreAuth = function(msg) {
                $rootScope.$broadcast("userNeedAuth", null);
                $location.path('/needauth');
            }

            $scope.$on("userLoggedOut", function(event, args) {
                account.clear();
                loadUser();
            });


            $scope.$on("userLoggedIn", function(event, args) {
                loadUser();
            });

            /* 用户访问该模块权限不够*/
            $scope.$on("userNeedAuth", function(event, args) {

            });

            /*新增*/
            $scope.$on("BUSY", function() {
                $scope.busy = true;
            });
            $scope.$on("NOTBUSY", function() {
                $scope.busy = false;
            });


        }).filter(
            //过滤器，用于获取获取时间的特殊格式
            'time_tiny', ['$sce', function($sce) {
                return function(text) {
                    return text.substr(-8, 8);
                }
            }]
        ).filter(
            'date_tiny', ['$sce', function($sce) {
                return function(text) {
                    return text.substr(5, 5);
                }
            }]
        ).filter(
            //过滤器，用于让文本中的HTML生效
            'to_trusted', ['$sce', function($sce) {
                return function(text) {
                    return $sce.trustAsHtml(text);
                }
            }]
        );

        return angularAMD.bootstrap(app);
        //return appCRM;
    });